//
//  UIColor+Extension.swift
//  KeyboardAndEmoji
//
//  Created by AP020Mac mini on 30-07-25.
//


import UIKit

extension UIColor {
    /// 通过十六进制字符串创建颜色，默认 alpha 为 1
    /// - Parameter hexString: 形如 "#RRGGBB"、"0xRRGGBB" 或 "RRGGBB" 的字符串
    /// - Returns: UIColor 实例，若格式不正确则返回 clear
   @objc static func color(hexString: String) -> UIColor {
        return color(hexString: hexString, alpha: 1.0)
    }

    /// 通过十六进制字符串和 alpha 创建颜色
    /// - Parameters:
    ///   - hexString: 形如 "#RRGGBB"、"0xRRGGBB" 或 "RRGGBB" 的字符串
    ///   - alpha: 透明度
    /// - Returns: UIColor 实例，若格式不正确则返回 clear
    @objc static func color(hexString: String, alpha: CGFloat) -> UIColor {
        var cString = hexString.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
        if cString.count < 6 {
            return .clear
        }
        if cString.hasPrefix("0X") {
            cString = String(cString.dropFirst(2))
        }
        if cString.hasPrefix("#") {
            cString = String(cString.dropFirst(1))
        }
        if cString.count != 6 {
            return .clear
        }
        let rString = cString.prefix(2)
        let gString = cString.dropFirst(2).prefix(2)
        let bString = cString.dropFirst(4).prefix(2)
        var r: UInt64 = 0, g: UInt64 = 0, b: UInt64 = 0
        Scanner(string: String(rString)).scanHexInt64(&r)
        Scanner(string: String(gString)).scanHexInt64(&g)
        Scanner(string: String(bString)).scanHexInt64(&b)
        return UIColor(red: CGFloat(r) / 255.0,
                       green: CGFloat(g) / 255.0,
                       blue: CGFloat(b) / 255.0,
                       alpha: alpha)
    }
    
    
   @objc convenience init?(hex: String) {
           var hexSanitized = hex.trimmingCharacters(in: .whitespacesAndNewlines)
           hexSanitized = hexSanitized.replacingOccurrences(of: "#", with: "")

           var rgb: UInt64 = 0
           var alpha: CGFloat = 1.0

           let length = hexSanitized.count

           guard Scanner(string: hexSanitized).scanHexInt64(&rgb) else {
               return nil
           }

           if length == 6 { // RRGGBB（无透明度）
               // 默认 alpha = 1.0
           } else if length == 8 { // RRGGBBAA（带透明度）
               alpha = CGFloat(rgb & 0xFF) / 255.0
               rgb >>= 8
           } else { // 格式错误
               return nil
           }

           let red = CGFloat((rgb & 0xFF0000) >> 16) / 255.0
           let green = CGFloat((rgb & 0x00FF00) >> 8) / 255.0
           let blue = CGFloat(rgb & 0x0000FF) / 255.0
//       UIColor.init(red: red, green: green, blue: blue, alpha: 1).withAlphaComponent(alpha)
//       let color = UIColor(red: red, green: green, blue: blue, alpha: 1)
//           self.init(cgColor: color.withAlphaComponent(alpha).cgColor)
//       self.init(red: red, green: green, blue: blue,alpha: 1).withAlphaComponent(alpha)
       self.init(red: red, green: green, blue: blue,alpha: alpha)
       }
    
    var isLight: Bool {
           guard let components = cgColor.components, components.count >= 3 else {
               return false
           }
           
           let red = components[0]
           let green = components[1]
           let blue = components[2]
           
           // 计算亮度 (使用感知亮度公式)
           let brightness = ((red * 299) + (green * 587) + (blue * 114)) / 1000
           
           return brightness > 0.5
       }
    
    
        func toHexString() -> String? {
            guard let components = cgColor.components, components.count >= 3 else {
                return nil
            }
            
            let r = Float(components[0])
            let g = Float(components[1])
            let b = Float(components[2])
            var a = Float(1.0)
            
            if components.count >= 4 {
                a = Float(components[3])
            }
            
            if a != 1.0 {
                return String(format: "#%02lX%02lX%02lX%02lX",
                             lroundf(r * 255),
                             lroundf(g * 255),
                             lroundf(b * 255),
                             lroundf(a * 255))
            } else {
                return String(format: "#%02lX%02lX%02lX",
                             lroundf(r * 255),
                             lroundf(g * 255),
                             lroundf(b * 255))
            }
        }
    
    // 生成随机颜色
    @objc static func randomColor() -> UIColor {
        let red = CGFloat(arc4random_uniform(256)) / 255.0
        let green = CGFloat(arc4random_uniform(256)) / 255.0
        let blue = CGFloat(arc4random_uniform(256)) / 255.0
        return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
    }
}
